package com.wyh.service.serviceImpl.g3serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.domain.po.g3po.G3Organization;
import com.wyh.domain.vo.g3vo.G3OrganizationVo;
import com.wyh.mapper.g3mapper.G3OrganizationMapper;
import com.wyh.service.g3service.IOrganizationService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织表 服务实现类
 * </p>
 *
 * @author 唐书亮
 * @since 2024-05-21
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<G3OrganizationMapper, G3Organization> implements IOrganizationService {

    @Override
    public G3OrganizationVo selectAllOrByName(String name) {
        G3OrganizationVo g3OrganizationVo = new G3OrganizationVo();
        //构造lambdaquery查询条件
        LambdaQueryWrapper<G3Organization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //当名字为空的时候,就直接查询所有组织
        lambdaQueryWrapper.like(name != null, G3Organization::getName, name);
        //查询
        List<G3Organization> list = this.list(lambdaQueryWrapper);
       //先将所有的父级组织拿出来
        List<G3Organization> fatherList = list.stream()
                .filter(Objects::nonNull)
                .filter(
                g3Organization -> {
                    return g3Organization.getSuperiorid() == 0;
                }
        ).collect(Collectors.toList());
            getChildren(list, fatherList);
        //将结果封装到vo中
        g3OrganizationVo.setG3OrganizationList(fatherList);
        return g3OrganizationVo;
    }

    public void getChildren(List<G3Organization> allList, List<G3Organization> fatherList) {
        //创建一个集合用来存放子级组织
        for (G3Organization father : fatherList) {
            //存放子级集合
            List<G3Organization> childrenList = new ArrayList<>();
            //遍历所有的组织,如果父级id等于当前遍历的id,就添加到子级集合中
            for (G3Organization g3Organization : allList) {
                //判断是否是子级
                if (father.getId().equals(g3Organization.getSuperiorid())) {
                    childrenList.add(g3Organization);
                }
                getChildren(allList, childrenList);
            }
            father.setChildren(childrenList);
        }

    }
}
